package com.ipharma.gui;

import javax.swing.JPanel;

import com.ipharma.McdError;
import com.ipharma.McdMain;
import com.ipharma.McdPrs;
import com.ipharma.config.Config;
import com.ipharma.config.Session;
import com.ipharma.config.TimeOut;

/**
 * A Swing-based top level window class.
 * <P>
 * 
 * @author JorgE.H
 */
public class GUIWindow extends JPanel implements Runnable {

   /**
    * Attributes
    */
   McdMain mcdMain;

   Session theSess;

   /* McdFunctionManager fm; */
   TimeOut to;

   Thread timer;

   /**
    * Constructs a new instance.
    */
   public GUIWindow(McdMain pMain) {

      super();
      try {
         mcdMain = pMain;
         theSess = mcdMain.session;
         // fm = new McdFunctionManager( theSess.getConn(),
         // theSess.getUser().getId(), McdPrs.mdeDispenser );
         jbInit();
      } catch (Exception e) {
         McdError.add(e);
      }
   }

   /**
    * Initializes the state of this instance.
    */
   private void jbInit() throws Exception {

   }

   /**
    * Starts execution
    * 
    * @param pMain
    *           the caller object
    */
   public void start() {

      this.setVisible(true);
   }

   /**
    * Stops execution, go back to menu
    */
   public void stop() {

      this.stopTimer();
      this.setVisible(false);
      mcdMain.start();
   }

   /**
    * Stops execution, go back to menu
    */
   public void finish() {

      this.stopTimer();
      this.setVisible(false);
   }

   /**
    * Timeout operations
    */
   public void timeout() {

      this.stop();
   }

   /**
    * Starts counting
    */
   public void startTimer() {

      Config config = (Config) theSess.get(McdPrs.CONFIG);
      to = new TimeOut(new Long(config.getTimeout()).longValue());
      timer = new Thread(this);
      timer.start();
   }

   /**
    * Kicks timer, setting it to initial state
    */
   public void kickTimer() {

      Config config = (Config) theSess.get(McdPrs.CONFIG);
      to.set(new Long(config.getTimeout()).longValue());
   }

   /**
    * Stops timer execution
    */
   public void stopTimer() {

      to.setValid(false);
   }

   /**
    * Timer thread code
    */
   public void run() {

      long secs = to.get();
      try {
         while (secs > 0 && to.isValid()) {
            timer.sleep(1000000); 
            System.out.println("timer expired!");
            this.timeout();
         }
      } catch (Exception e) {
         McdError.add(e);
      }

   }
}